console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';
import { startZeroReport, checkZeroReport } from './zeroReport.js';
import { insertJQuery } from '../../lib/utils.js';

function changeInputData(el, value) {
  let copySetValue = Object.getOwnPropertyDescriptor(
    window.HTMLInputElement.prototype,
    'value'
  ).set;
  copySetValue.call(el, value);
  let e = new Event('input', { bubbles: true });
  el.dispatchEvent(e);
}

async function waitTimeOut(timeout = 1000) {
  return new Promise(function (resolve, reject) {
    setTimeout(() => {
      resolve();
    }, timeout);
  });
}

let baseInfo,
  isGetInfo = true;
let getInfo = () => {
  window.postMessage(
    {
      event: 'getZeroInfo'
    },
    '*'
  );
  console.log('getZeroInfo');
  checkZeroReport();
};

(() => {
  console.log(123);
  if (!window.jQuery) {

    console.log(123);
    isGetInfo = false;
    insertJQuery();
    return;
  }
  $(window).ready(getInfo);
})();

window.onload = function () {
  // 登录填写账号密码
  if (/\/beforeLogin\/indexBefore/g.test(window.location.pathname)) {
    window.postMessage({
      event: 'getBaseInfo'
    }, '*');
  }

  if (!isGetInfo) {
    getInfo();
  }

  // 获取申报周期
  if (/jumpMain.action/g.test(window.location.pathname)) {
    $('body').on('click', '[sbzt]', function () {
      let $this = $(this);
      let id = $this.attr('id') || '';

      // 获取申报周期
      let sssq_q = $this.attr('sssq_q') || '';
      let sssq_z = $this.attr('sssq_z') || '';


      // 获取申报周期，填充数据
      let period = getReportingCycle(sssq_q, sssq_z);
      // 获取税类型
      let title = $this.data('title');
      let taxType = getTaxType(id, title);

      // 财务报表上的tab 绑定事件
      tabBindClick(id, title);


      sssq_q = period.sssq_q;
      sssq_z = period.sssq_z;


      if (sssq_q && sssq_z) {
        window.postMessage({
          event: 'setPeriodAndType',
          data: {
            type: taxType,
            startTime: sssq_q,
            endTime: sssq_z
          }
        }, '*');
      }
    });
  }
};


window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    fillInput(await transformDataByOpenWeb(data.data));
  }
  if (data.event === 'getNationData') {
    getNationData();
  }

  if (data.event === 'getBaseInfo') {
    baseInfo = data.data;
    console.log(baseInfo)
    autoInputAccount(baseInfo);
  }

  if (data.event === 'getZeroInfoBack') {
    if (data.data.isOpenZeroReport) {
      let backInfo = await startZeroReport(data);
    }
  }
  if (data.event === 'zeroReportEnd') {
    console.log('zeroReportEnd', data);
    if (data.data.data.isSuccess) {
      setTimeout(() => {
        window.postMessage(
          {
            event: 'asyncTableDetailRequest'
          },
          '*'
        );
      }, 100);
    }
    setTimeout(() => {
      window.postMessage(
        {
          event: 'clearZeroReport'
        },
        '*'
      );
      window.sessionStorage.clear();
      window.loginOut();
    }, 3000);
  }
}, false);
/**
 * 获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: '2013', // 国税对应制度 2007 | 2013
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: ''// 税款所属期止
  };
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

async function autoInputAccount({ companyInfo }) {
  if (/\/beforeLogin\/indexBefore/g.test(window.location.pathname)) {
    $('.mini-tools-close').click();
  }
  companyInfo = companyInfo || {};
  console.log(companyInfo);
  let { nationalTaxAccount, nationalTaxId, nationalTaxPass } = companyInfo;
  if (!nationalTaxPass) {
    notifications('没有从系统获取到密码,请自行填写');
  }
  let ursername = document.querySelectorAll("#formDivCls input")
  // ursername[0].value = nationalTaxId;
  changeInputData(ursername[0], nationalTaxId);
  changeInputData(ursername[1], nationalTaxAccount);
  changeInputData(ursername[2], nationalTaxPass);
  // if (window.goLogin) {
  //   // 点击登录
  //   window.goLogin();
  //   $('#userName').focus();
  //   try {
  //     // debugger
  //     changeInputData($('#userName')[0], nationalTaxId || nationalTaxAccount);
  //     $('#userName').blur();
  //     $('#passWord').focus();
  //     await waitTimeOut(1000);
  //     changeInputData($('#passWord')[0], nationalTaxPass);
  //   } catch (error) {
  //     // notifications('税局登录界面打开异常,请刷新网页或者重新跳转到税局');
  //     console.log(error);
  //   }
  // }
  // companyInfo = companyInfo || {};
  // console.log(companyInfo);
  // let { nationalTaxAccount, nationalTaxId, nationalTaxPass } = companyInfo;
  // if (window.goLogin) {
  //   window.goLogin();
  //   setTimeout(()=>{
  //     let userName = $('#userName'),
  //       password = $('#passWord');
  //       userName.val(nationalTaxAccount || nationalTaxId)
  //       password.val(nationalTaxPass)
  //     // userName.closest('section').append(nationalTaxAccount + '<br/>');

  //     // password.closest('section').append(nationalTaxPass);
  //   }, 500);
  //   return true;
  // }
  // $('#loginForm').contents().find('.Name_ipt').val(companyInfo.nationalTaxAccount || companyInfo.nationalTaxId);
  // $('.pwd_ipt').css('display', 'inline').val(companyInfo.nationalTaxPass).removeAttr('onblur onfocus');
}

function fillInput({ saasData }) {
  let sheetType = saasData.sheetType;
  let iframeWindow;
  if (sheetType === 'cwbb') {
    iframeWindow = window;
  } else {
    iframeWindow = $('#ndsdsa2017_iframe')[0].contentWindow;
  }
  let message = '填报成功';
  try {
    let inputData = saasData.data;
    for (let key in inputData) {
      let value = Number.parseFloat(inputData[key]).toFixed(2) || '0.00';
      let $input = iframeWindow.$(`input#${key}`);
      if ($input.length !== 0) {
        $input.closest('tr').find("[name$='czbz']").val('update');
        $input.val(value).trigger('blur');
      }
    }
    if (sheetType !== 'cwbb') {
      // 各种合计
      iframeWindow.SDSNDA_Formula_45ToJs();
      iframeWindow.SDSNDA_Formula_74ToJs();
      iframeWindow.SDSNDA_Formula_75ToJs();
      iframeWindow.SDSNDA_Formula_76ToJs();
      iframeWindow.SDSNDA_Formula_77ToJs();
      iframeWindow.SDSNDA_Formula_78ToJs();
      iframeWindow.SDSNDA_Formula_79ToJs();

      iframeWindow.SDSNDA_Formula_47ToJs();

      iframeWindow.SDSNDA_Formula_57ToJs();
      iframeWindow.SDSNDA_Formula_58ToJs();
      iframeWindow.SDSNDA_Formula_59ToJs();

      iframeWindow.SDSNDA_Formula_300ToJs();
      iframeWindow.SDSNDA_Formula_1212ToJs();
      iframeWindow.SDSNDA_Formula_302ToJs();
      iframeWindow.SDSNDA_Formula_313ToJs();
    }
  } catch (e) {
    message = '填报失败' + e;
  }

  // todo finally
  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message
    }
  }, '*');
}

/**
 * @param startDate 开始时间
 * @param endDate 结束时间
 * 获取申报周期并且填充数据
 */
function getReportingCycle(startDate, endDate) {
  var sssq_q = (startDate && startDate.substr(0, 7).replace('-', ''));
  var sssq_z = (endDate && endDate.substr(0, 7).replace('-', ''));

  return {
    sssq_q: sssq_q,
    sssq_z: sssq_z
  };
}


/**
 * 获取 税类型 用于填充填报类型
 * @param id
 * @returns {string}
 */

function getTaxType(id = '', title) {
  let taxType = 'zzs';

  if (id.search('zzs') != -1) {
    taxType = 'zzs';
  } else if (id.search('sds') != -1) {
    taxType = 'sds';
  }

  if (title.search('财务报表') != -1) {
    let text = $('#' + id + '_iframe').contents().find('#tab-ul').find('li.active')
      .text() || '';
    if (text.search('资产负债表') != -1) {
      taxType = 'balance';
    } else if (text.search('利润表') != -1) {
      taxType = 'profit';
    } else if (text.search('现金流量表') != -1) {
      taxType = 'cashing';
    } else {
      taxType = 'balance';
    }
  }
  return taxType;
}

/**
 * 绑定方法
 * @param id
 */
function bindTab(id) {
  var $iframe = $('#' + id + '_iframe');
  $iframe[0].contentWindow.$('body').on('click', 'li.active', function () {
    var taxType = getTaxType(id, '财务报表');
    // eslint-disable-next-line no-undef
    ipcRenderer.sendToHost('send-filter', {
      type: taxType
    });
  });
}

/**
 * 绑定tab切换事件
 * @param id
 * @param title
 */
function tabBindClick(id, title) {
  document.getElementById(id + '_iframe').onload = function () {
    if (title.search('财务报表') != -1) {
      bindTab(id);
    }
  };
}
